package net.ondev.dutils.tostring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;

public class ToStringCodesGenerator {

	static Log log=LogFactory.getLog(ToStringCodesGenerator.class);
	
	public void generateToStringMethod(IType type, boolean useWorkingCopy){
		generateToStringMethod(type, false, useWorkingCopy);
	}
	
	public void generateToStringMethod(IType type, boolean overwrite, boolean useWorkingCopy){
		if(type == null){
			return;
		}
		
		String methodBodyText = "public String toString(){\n" + 
			"    StringBuilder result = new StringBuilder();\n" +
			"    String NEW_LINE = System.getProperty(\"line.separator\" );\n" +
			"    result.append(this.getClass().getName() + \" Object {\" + NEW_LINE );\n" ;
			

		try {
			if(type.isClass()){
				
				IField[] fields = type.getFields();
				for(IField field: fields){
					methodBodyText += "    result.append(\" " + field.getElementName() + ": \" + " + field.getElementName() + " + NEW_LINE );\n";
				}
			}
		} catch (JavaModelException e) {
			log.error(e);
		}
		methodBodyText += "    result.append(\"}\" );\n"
				+ "    return result.toString();\n"
				+ "}\n";
		
		
		createMethod(type, methodBodyText, overwrite);
	}

	/**
	 * @param type
	 * @param methodBodyText
	 */
	private void createMethod(IType type, String methodBodyText, boolean overwrite) {
		try {
			IMethod method = type.createMethod(methodBodyText, null, overwrite, null);
		} catch (JavaModelException e) {
			log.error(e);
		}
	}
	
	public void generateToStringMethod(ICompilationUnit unit, boolean useWorkingCopy){
		try {
			ICompilationUnit workingCopy = unit;
			if(useWorkingCopy){
				workingCopy = unit.getWorkingCopy(null);
			}
			IType[] types = unit.getAllTypes();
			if(types != null){
				for(IType type: types){
					generateToStringMethod(type, true);
				}
			}
		} catch (JavaModelException e) {
			log.error(e);
		}
	}
}
